import * as fs from 'fs'
// import { logger } from 'vs/platform/issue/electron-main/logger';
//读取JSON数据，并将其转换为对象格式
/**
 *
 * @param filePath 文件路径
 * @returns 对象
 */
export function readJSON(filePath: string): any {
	// logger.debug("readJSON");
	try {
		// logger.debug("readJSON" + filePath);
		let Object = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
		return Object;
	} catch {
		// logger.debug("readJSON,null");
		return null;
	}
}

//获取JSONObject中属性Key对象
/**
 *
 * @param key 属性名称
 * @param JSONObject  需要检查的对象
 * @returns  返回JSONObject中属性Key对象
 */
export function getKeyObject(key: string, JSONObject: any): any {
	if (JSONObject && JSONObject.hasOwnProperty("second_class") && JSONObject["second_class"].hasOwnProperty(key)) {
		return JSONObject["second_class"][key];
	}
	return null;
}

/**
 *
 * @param key 属性
 * @param filePath  文件路径
 * @returns 返回文件中属性为key的对象中定义的go包的信息
 */
export function getListGoFromKey(key: string, filePath: string): any[] {

	// logger.debug("getListGoFromKey");

	let goInfoArry: any[] = [];
	const JSONObject = readJSON(filePath);
	if (JSONObject) {
		const goObject = getKeyObject(key, JSONObject);
		if (goObject && goObject.hasOwnProperty("pkg-list") && goObject["pkg-list"].hasOwnProperty("go"))
			Object.keys(goObject["pkg-list"]["go"]).forEach(function (item) {
				let tmp: any = {};
				tmp.url = goObject["pkg-list"]["go"][item].url;
				tmp.status = "notdownload";
				goInfoArry.push(tmp);
			})
	}
	// goInfoArry.forEach(function (item) {
	// 	logger.debug("getListGoFromKey" + item.url);
	// });
	// logger.debug("getListGoFromKey,end");
	return goInfoArry;
}

/**
 *
 * @param key 属性
 * @param filePath 文件路径
 * @returns 返回文件中属性为key的对象中定义的pip3相关包的信息
 */
export function getListPip3FromKey(key: string, filePath: string): any[] {
	let pip3InfoArry: any[] = [];
	const JSONObject = readJSON(filePath);
	if (JSONObject) {
		const pip3Object = getKeyObject(key, JSONObject);
		if (pip3Object && pip3Object.hasOwnProperty("pkg-list") && pip3Object["pkg-list"].hasOwnProperty("pip3"))
			Object.keys(pip3Object["pkg-list"]["pip3"]).forEach(function (item) {
				let tmp: any = {};
				tmp.url = pip3Object["pkg-list"]["pip3"][item].url;
				tmp.name = pip3Object["pkg-list"]["pip3"][item].name;
				tmp.status = "notdownload";
				pip3InfoArry.push(tmp);
			})
	}
	return pip3InfoArry;
}

export function getPkgListFromKey(key: string, object: any): string[] {
	let resArry: string[] = [];
	for (let item in object) {
		resArry.push(...object[item]["pkg-list"]);
	}
	return resArry;
}
